import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useCallback, useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Select, DatePicker, TreeSelect, Space, Button, Checkbox, Tooltip, Modal } from 'antd';
import { UploadFormCommon } from '@/components/UploadForm';
import {
  downloadTemplate,
  fieldFlowExport,
  getCompanyID,
  getCompanyName,
  getFileNameNotType,
  getInvoiceCode,
  getLevelZeroJson,
  getLoadMapList,
  getPersonalInfo,
  getPosIDs,
  getPosName,
  getSelectDataMapList,
  getTenantID,
  getUserDepID,
  getUserDepName,
  getUserID,
  getUserName,
  splitFileUrl,
} from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { SaveOutlined, CheckCircleOutlined, DownloadOutlined, UploadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { DetailServices, EditServices, ExportdetServices, addServices, approvedInventorySerivice } from '../services';
import moment from 'moment';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { orderType, requestController } from '../common/Format';
import Detailed from './Detailed';
import MyIcon from '@/components/MyIcon';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '@/pages/PurchaseManage/Acomponents/RevokeModal';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

function addDisabledToTreeData(originalTreeData) {
  const newTreeData = originalTreeData?.map((node) => {
    const newNode = { ...node, disabled: true }; // 复制节点并添加disabled属性

    if (node.children) {
      newNode.children = addDisabledToTreeData(node.children); // 递归处理子节点
    }

    return newNode;
  });

  return newTreeData;
}

const UpdataView: React.FC<any> = ({ curRes, locationProps }) => {

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };
  
  const { pageType } = locationProps?.state;
  const isDetail = pageType === 'detail';
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';
  const [rangeDeptID, setRangeDeptID] = useState<any>('');
  const [rangeAssetTypeID, setRangeAssetTypeID] = useState('');
  const [detailprams, setDetailprams] = useState<any>();
  const [detailId, setDetailId] = useState(null);
  const [detailInfo, setDetailInfo] = useState<Record<string, any>>({}); /**详情对象*/
  const [activeKey, setActiveKey] = useState('001');

  /** 是否提交 */
  const [isSubmit, setIsSubmit] = useState<boolean>(false);

  /** 详情数据 */
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  /** 选中的盘点开始时间 */
  const [startTime, setStartTime] = useState<any>('');

  /** 选中的取得开始时间 */
  const [getStartTime, setGetStartTime] = useState<any>('');

  const [acceptForm] = Form.useForm();

  const range = (start: any, end: any) => {
    const result: any = [];
    for (let i = start; i < end; i += 1) {
      result.push(i);
    }
    return result;
  };

  // 不可选择盘点开始以前的时间
  const disabledDate = (current: any) => {
    if (current && startTime && current < startTime.startOf('day')) {
      return true;
    } else {
      return false;
    }
  };

  // 不可选择取得开始以前的时间
  const disabledGetDate = (current: any) => {
    if (current && getStartTime && current < getStartTime.startOf('day')) {
      return true;
    } else {
      return false;
    }
  };

  const disabledTime = (date: any) => {
    const hours = moment().hours();
    const minutes = moment().minutes();
    const seconds = moment().seconds();
    // 当日只能选择当前时间之后的时间点
    if (date && moment(date)?.date() - 1 === moment()?.date() - 1) {
      return {
        disabledHours: () => range(0, 24).splice(0, hours),
        disabledMinutes: () => range(0, 60).splice(0, minutes + 1),
        disabledSeconds: () => range(0, 60).splice(0, seconds + 1),
      };
    }
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    };
  };

  /** 审核通过后为true */
  const [auditSuccessState, setAuditSuccessState] = useState(false);

  const { DetailPushRun, Detaildata, getDetailReload, DetailPushLoading } = DetailServices(curRes, (res) => {
    if (res?.msgFlag) {
      setDetailInfo(res?.obj);

      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1001`
      ) {
        setAuditSuccessState(true);
      }

      message.success(res?.msg);
    }
  });
  const disabled: boolean = pageType === 'detail';

  /** 表单配置项 */
  const fromArray: any = useCallback(() => {
    return [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: isDetail,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },

          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '申请人',
            field: 'createrName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '联系电话',
            field: 'createPhone',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '申请部门/单位',
            field: 'createDepartmentName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '职务岗位',
            field: 'createPositionName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `startTime`,
            label: `盘点开始时间`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            placeholder: '请输入',
            render: (text) => {
              if (isDetail) {
                return text ? moment(text).format('YYYY-MM-DD') : '--';
              } else {
                return (
                  <DatePicker
                    format={'YYYY-MM-DD'}
                    disabledTime={disabledTime}
                    onChange={(value: any) => {
                      setStartTime(value);
                    }}
                  />
                );
              }
            },
          },
          {
            field: `endTime`,
            label: `盘点结束时间`,
            component: 'Render',
            disabled: isDetail,
            required: !isDetail,
            placeholder: '请输入',
            render: (text) => {
              if (isDetail) {
                return text ? moment(text).format('YYYY-MM-DD') : '--';
              } else {
                return <DatePicker format={'YYYY-MM-DD'} disabledDate={disabledDate} />;
              }
            },
          },
          {
            field: `rangeDeptID`,
            label: `部门范围`,
            component: 'Render',
            required: !isDetail,
            colSpan: 2,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder={`请选择`}
                  multiple
                  style={{
                    width: '100%',
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'text',
                    value: 'id',
                    children: 'children',
                  }}
                  onChange={(value) => {
                    function getAllChildrenIds(treeData, targetIds) {
                      const allIds = new Array();

                      // Helper function to recursively get all children's IDs
                      function getChildrenIds(node) {
                        allIds.push(node.id);
                        if (node.children) {
                          node.children.forEach((child) => getChildrenIds(child));
                        }
                      }

                      // Find the target nodes and get their children's IDs
                      function findTargets(node) {
                        if (targetIds.includes(node.id)) {
                          getChildrenIds(node);
                        } else if (node.children) {
                          node.children.forEach((child) => findTargets(child));
                        }
                      }

                      // Start the search
                      treeData.forEach((node) => findTargets(node));

                      return allIds;
                    }

                    acceptForm.setFieldsValue({
                      rangeDeptID: getAllChildrenIds(getLevelZeroJson(), value),
                    });
                  }}
                  disabled={isDetail}
                  treeData={getLevelZeroJson()}
                  treeCheckable={true}
                  maxTagCount={5}
                  showCheckedStrategy={TreeSelect.SHOW_PARENT}
                  treeDefaultExpandAll={isDetail ? true : false}
                />
              );
            },
          },
          {
            field: `rangeAssetClassID`,
            label: `资产类型范围`,
            component: 'Render',
            required: !isDetail,
            colSpan: 2,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder={`请选择`}
                  value={text}
                  multiple
                  style={{
                    width: '100%',
                  }}
                  onChange={(value) => {
                    setRangeAssetTypeID(value);
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  disabled={isDetail}
                  treeData={isDetail ? addDisabledToTreeData(assetType) : assetType}
                  treeCheckable={true}
                  maxTagCount={3}
                />
              );
            },
          },
          {
            field: `rangeStartDate`,
            label: `取得开始时间`,
            component: 'Render',
            colSpan: 1,
            disabled: isDetail,
            placeholder: '请输入',
            render: (text) => {
              if (isDetail) {
                return text ? moment(text).format('YYYY-MM-DD') : '--';
              }
              return (
                <DatePicker
                  format={'YYYY-MM-DD'}
                  onChange={(value: any) => {
                    setGetStartTime(value);
                  }}
                />
              );
            },
          },
          {
            field: `rangeEndDate`,
            label: `取得结束时间`,
            component: 'Render',
            colSpan: 1,
            disabled: isDetail,
            placeholder: '请输入',
            render: (text) => {
              if (isDetail) {
                return text ? moment(text).format('YYYY-MM-DD') : '--';
              }
              return <DatePicker format={'YYYY-MM-DD'} disabledDate={disabledGetDate} />;
            },
          },
          {
            field: `inventoryInfo`,
            label: `盘点说明`,
            component: 'InputTextArea',
            disabled: isDetail,
            placeholder: '请输入',
            required: !isDetail,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `reportURL`,
            label: `相关附件`,
            component: 'Render',
            disabled: isDetail,
            colSpan: 2,
            placeholder: '请输入',
            render: (text, record) => {
              return !isDetail ? (
                <UploadFormCommon
                  form={acceptForm}
                  fileFormName={'reportURL'}
                  spanCol={12}
                  inRowProportion={24}
                  name={'attachFile'}
                  required={false}
                  // accept={'.doc|.docx'}
                  url={'/assetInfo/uploadFile'}
                  downloadUrl={'/assetInfo/downloadFile'}
                  fileFormDelName={'delFile'}
                  uploadSuccessCallback={(attachPaths) => {
                    acceptForm?.setFieldsValue({
                      reportURL: attachPaths,
                    });
                  }}
                  defaultFiles={text}
                  // maxFile={1}
                  // hintTitle={'且只能上传 1 个！'}
                  fieldBusiPath={'reportURL'}
                  delFunc={(delFilePath) => {
                    // acceptForm?.setFieldsValue({
                    //   assetImage: '',
                    // });
                  }}
                >
                  上传
                </UploadFormCommon>
              ) : (
                <div
                  style={{
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    marginLeft: '8px',
                  }}
                >
                  {record?.['reportURL']
                    ? splitFileUrl(record?.['reportURL'])?.map((e, i) => {
                        return (
                          <div>
                            <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                              <a
                                onClick={() => {
                                  message.success('下载中，请稍后...');
                                  downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                }}
                              >
                                <MyIcon type="icon-file-text-fill" />
                                &nbsp;
                                {getFileNameNotType(e.attachName, 8)}
                              </a>
                            </Tooltip>
                            {/* 轻阅读预览 */}
                            <Tooltip title={'在线预览'}>
                              <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                            </Tooltip>
                          </div>
                        );
                      })
                    : '--'}
                </div>
              );
            },
          },
          {
            field: `inventoryTitle`,
            label: `事项名称`,
            component: 'Input',
            required: !isDetail,
            disabled: isDetail,
            placeholder: '请输入',
            colSpan: 0,
          },
        ],
      },
    ];
  }, [assetType]);

  /** 初始化页面 */
  useEffect(() => {
    if (detailInfo?.id) {
      // 回填表单
      acceptForm?.setFieldsValue({
        ...detailInfo,
        createTime: moment(detailInfo?.createTime),
        rangeDeptID: Detaildata?.obj?.rangeDeptID?.split(','),
        rangeAssetClassID: Detaildata?.obj?.rangeAssetClassID?.split(','),
        startTime: moment(detailInfo?.startTime, 'YYYY-MM-DD'),
        endTime: moment(detailInfo?.endTime, 'YYYY-MM-DD'),
        rangeStartDate: detailInfo?.rangeStartDate ? moment(detailInfo?.rangeStartDate, 'YYYY-MM-DD') : '',
        rangeEndDate: detailInfo?.rangeEndDate ? moment(detailInfo?.rangeEndDate, 'YYYY-MM-DD') : '',
        rangeDeptPID: detailInfo?.rangeDeptID.split(','),
      });
    } else {
      acceptForm?.setFieldsValue({
        inventoryTitle: `${getUserName()}_${getUserDepName()}_${moment(new Date()).format('YYYY年_MM月')}_盘点计划`,
        createTime: moment(new Date()),
        applyCode: getInvoiceCode('PDJH'),
        createrName: getUserName(),
        createPhone: getPersonalInfo()?.phoneMobile || '',
        createDepartmentName: getUserDepName(),
        createPositionName: getPosName(),
      });
    }
  }, [detailInfo]);

  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: acceptForm,
    schemas: fromArray(),
  });

  /** 添加编辑回调*/
  const saveCallback = (res: any) => {
    if (res.msgFlag) {
      message.success(res.msg);
      if (isSubmit) {
        setWorkFlowInfoObj({
          selectFlowRows: res.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        history.push({
          pathname: '/inventoryPlanController/manage',
          state: {
            delRouterNameSource: history.location.pathname,
          },
        });
      }
    } else {
      message.error(res.msg);
    }
  };

  /** 添加 */
  const { addPushRun, addPushLoading } = addServices(curRes, saveCallback);

  /** 编辑 */
  const { EditPushRun, EditPushLoading } = EditServices(curRes, saveCallback);

  // 工作流
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);

  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (Detaildata?.state == `${getTenantID()}${ILoadMapTypeAll?.ASSET_INPLAY_STATUS}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`;
    const taskHandInfo: Record<string, any> = Detaildata?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [Detaildata]);

  const [titleValue, setTitleValue] = useState(null);

  const changeTitleValue = (value: any) => {
    setTitleValue(value);
  };

  // 导出接口
  const { ExportRun, ExportPushLoading } = ExportdetServices((res: any) => {
    fieldFlowExport(res, `${titleValue}.xlsx`);
  }, curRes);

  /** 审核通过后要调的接口 */
  const { approvedInventoryRun, approvedInventoryLoading } = approvedInventorySerivice((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/inventoryPlanController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    }
  });

  /** 监听审核状态-审核通过后调用同步接口 */
  useEffect(() => {
    if (
      auditSuccessState &&
      detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1003`
    ) {
      approvedInventoryRun({ ...detailInfo, workflowResult: true });
    }
  }, [detailInfo?.checkState, detailInfo?.state]);

  useEffect(() => {
    if (locationProps.state.id) {
      const obj: any = {
        id: locationProps.state.id,
      };
      DetailPushRun(obj);
    } else if (locationProps.state.record) {
      DetailPushRun(locationProps.state.record);
    }
  }, [locationProps.state]);

  useEffect(() => {
    if (detailId) {
      const obj: any = {
        id: detailId,
      };
      DetailPushRun(obj);
    }
  }, [detailId]);

  /** 暂存 */
  const saveFun = (flag: boolean) => {
    if (locationProps?.state?.pageType == 'add' && !detailId && !flag) {
      acceptForm.validateFields()?.then((res) => {
        const obj = acceptForm.getFieldsValue();
        // 校验时间先后
        const isBefore = moment(obj?.endTime).isBefore(moment(obj?.startTime));
        if (isBefore) {
          message.error('盘点结束时间不能早于盘点开始时间！');
          return;
        }
        const isBefore2 = moment(obj?.rangeEndDate).isBefore(moment(obj?.rangeStartDate));
        if (isBefore2) {
          message.error('取得结束时间不能早于取得开始时间！');
          return;
        }
        obj.endTime = moment(obj?.endTime).format('YYYY-MM-DD HH:mm:ss');
        obj.startTime = moment(obj?.startTime).format('YYYY-MM-DD HH:mm:ss');
        obj.rangeStartDate = obj?.rangeStartDate ? moment(obj?.rangeStartDate).format('YYYY-MM-DD HH:mm:ss') : '';
        obj.rangeEndDate = obj?.rangeEndDate ? moment(obj?.rangeEndDate).format('YYYY-MM-DD HH:mm:ss') : '';

        if (obj?.rangeAssetClassID?.length > 0) {
          obj.rangeAssetClassID = obj?.rangeAssetClassID?.join();
        }

        if (obj?.rangeDeptID?.length > 0) {
          obj.rangeDeptID = obj?.rangeDeptID?.join();
        }

        const pramobj: any = {
          ...obj,
          createTime: moment(obj?.createTime).format('YYYY-MM-DD HH:mm:ss'),
          createrID: getUserID(),
          createPositionID: getPosIDs(),
          createCompanyID: getCompanyID(),
          createDepartmentID: getUserDepID(),
        };
        addPushRun(pramobj);
      });
    } else if (locationProps?.state?.pageType == 'edit' || detailId || flag) {
      acceptForm.validateFields()?.then((res) => {
        const obj = acceptForm.getFieldsValue();
        // 校验时间先后
        const isBefore = moment(obj?.endTime).isBefore(moment(obj?.startTime));
        if (isBefore) {
          message.error('盘点结束时间不能早于盘点开始时间！');
          return;
        }
        const isBefore2 = moment(obj?.rangeEndDate).isBefore(moment(obj?.rangeStartDate));
        if (isBefore2) {
          message.error('取得结束时间不能早于取得开始时间！');
          return;
        }
        obj.endTime = moment(obj?.endTime).format('YYYY-MM-DD HH:mm:ss');
        obj.startTime = moment(obj?.startTime).format('YYYY-MM-DD HH:mm:ss');
        obj.rangeStartDate = obj?.rangeStartDate ? moment(obj?.rangeStartDate).format('YYYY-MM-DD HH:mm:ss') : '';
        obj.rangeEndDate = obj?.rangeEndDate ? moment(obj?.rangeEndDate).format('YYYY-MM-DD HH:mm:ss') : '';

        if (obj?.rangeAssetClassID?.length > 0) {
          obj.rangeAssetClassID = obj?.rangeAssetClassID.join();
        }

        if (obj?.rangeDeptID?.length > 0) {
          obj.rangeDeptID = obj?.rangeDeptID.join();
        }
        const pramobj: any = {
          ...obj,
          id: Detaildata?.obj?.id,
          createTime: moment(obj?.createTime).format('YYYY-MM-DD HH:mm:ss'),
          modifyerID: getUserID(),
          modifyerName: getUserName(),
          modifyPositionID: getPosIDs(),
          modifyPositionName: getPosName(),
          modifyCompanyID: getCompanyID(),
          modifyCompanyName: getCompanyName(),
          modifyDepartmentID: getUserDepID(),
          modifyDepartmentName: getUserDepName(),
          // createTime: moment(obj.createTime).format('YYYY-MM-DD HH:mm:ss'),
        };
        // delete pramobj?.createTime;
        EditPushRun(pramobj);
      });
    }
  };

  const changeIsSubmit = () => {
    setIsSubmit(true);
  };
  
  /** 申请页ref */
  const { confirm } = Modal;

  const handleClose = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = useMemo(() => {
    let items: any[] = [
      {
        label: '申请详情',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>

            <div
              className="tabsBodyBottomBtn"
              style={{
                textAlign: 'center',
              }}
            >
              <Space>
                {((!detailInfo?.state ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1000` && !detailInfo?.checkState) ||
                  (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1003` &&
                    detailInfo?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1003`)) &&
                detailInfo?.createrID == getUserID())|| locationProps?.state?.pageType === 'add' ? (
                  <Button
                    type={'primary'}
                    onClick={() => {
                      saveFun(locationProps?.state?.pageType == 'add' ? false : true);
                      changeIsSubmit();
                    }}
                  >
                    提交
                  </Button>
                ) : null}
                <Button danger onClick={handleClose}>
                      关闭
                    </Button>
                {/* <WorkflowHndTaskBtn
                  flowDetailInfo={detailInfo}
                  requestController={'assetInventory'}
                  reloadCallback={getDetailReload}
                  flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`}
                /> */}
              </Space>
            </div>
          </div>
        ),
      },
      {
        label: '盘点明细',
        key: '002',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <Detailed datalist={{ ...Detaildata?.obj }} />
              </ScrollBarLayout>
            </div>

            {/* <div
              className="tabsBodyBottomBtn"
              style={{
                textAlign: 'center',
              }}
            >
              <Space>
                <Button
                  icon={<DownloadOutlined />}
                  style={{ marginBottom: 24 }}
                  type={'primary'}
                  onClick={() => {
                    setTitleValue(Detaildata?.obj.inventoryTitle);
                    const obj: any = {
                      inventoryID: Detaildata?.obj.id,
                    };
                    ExportRun(obj);
                  }}
                >
                  导出
                </Button>
              </Space>
            </div> */}
          </div>
        ),
      },
    ];
    return items;
  }, [rangeDeptID, rangeAssetTypeID, workFlowInfoObj, detailprams, detailId, Detaildata, assetType]);

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        position="top"
        detailInfo={detailInfo}
        getDetailReload={getDetailReload}
        locationProps={locationProps}
        detailId={detailId}
        saveFun={saveFun}
        Detaildata={Detaildata}
        activeKey={activeKey}
        ExportRun={ExportRun}
        changeTitleValue={changeTitleValue}
        changeIsSubmit={changeIsSubmit}
        changeRevoke={changeRevoke}
      />
    );
  };

  return (
    <>
      <div className={'apply-update-UpdataIntentBox'}>
        <Spin spinning={mapLoading || DetailPushLoading || ExportPushLoading || approvedInventoryLoading}>
          <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
            <Col span={24} className={`${styleFixCls}row-col`} style={{ position: 'relative' }}>
              <Tabs
                className={pageStyles['commonTabs']}
                type="card"
                onChange={(activeKey: string) => {
                  setActiveKey(activeKey);
                }}
                items={tabsItem}
                destroyInactiveTabPane={true}
                tabBarExtraContent={contactsTabsExtra()}
              />
              {
                // 盘点明细导出按钮
              }
              {/* {Detaildata && activeKey === '002' && (
                <div className="tabsBodyBottomBtn" style={{ position: 'absolute', top: 5, right: 8 }}>
                  <Space>
                    <Button
                      type={'primary'}
                      icon={<DownloadOutlined />}
                      onClick={() => {
                        setTitleValue(Detaildata?.obj.inventoryTitle);
                        const obj: any = {
                          inventoryID: Detaildata?.obj.id,
                        };
                        ExportRun(obj);
                      }}
                    >
                      导出
                    </Button>
                  </Space>
                </div>
              )} */}
            </Col>
          </Row>

          {/* 撤销弹窗 */}
          {invalidState?.isShow && (
            <RevokeModal
              resObj={invalidState?.resObj}
              revokeRequestUrl={'/assetInventory/revoke'}
              onClose={() => setInvalidState({})}
              reqBody={{
                id: invalidState?.resObj?.id,
                state: `${getTenantID()}${ILoadMapTypeAll?.ASSET_INPLAY_STATUS}1000`,
                inventoryState: `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1000`,
              }}
              modalTip={
                <div style={{ color: '#000' }}>
                  确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.inventoryTitle}</span>】的审核, 撤销后可重新提交！
                </div>
              }
              reloadRequest={() => {
                history.push({
                  pathname: locationProps?.state?.returnPathName,
                  state: {
                    delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                    returnPathName: locationProps?.state?.returnPathName,
                  },
                });
              }}
            />
          )}

          {/* 工作流-----审批记录 */}
          {Detaildata?.obj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`] && activeKey == '001' && (
            <WorkflowChedkRecord
              curRes={curRes}
              dataDetailInfo={Detaildata?.obj}
              flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`}
              requestController={requestController()}
              reloadPageCallback={() => {
                DetailPushRun({ ...Detaildata?.obj });
              }} // 刷新方法-详情方法
              revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.ASSET_INPLAY_STATUS}1000`}
              allBtnFuncQuqry={workflowPowerAllBtn}
              tabPaneHeight={0.35}
              isCheckDrawer={true}
              isShowCollapse={isShowWorkRecord}
              changeCollapse={(val) => {
                setIsShowWorkRecord(val);
              }}
              cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.ASSET_INPLAY_STATUS}1003`}
              isSyncArchive={true}
            />
          )}

          {/* 工作流-----发起流程审批弹窗 */}
          {workFlowInfoObj?.showWorkFlowModal && (
            <WorkflowSwitchModal
              openVisible={workFlowInfoObj?.showWorkFlowModal}
              businessInfoObj={workFlowInfoObj?.selectFlowRows}
              requestController={requestController()}
              orderType={orderType()}
              category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`}
              businessCategory={''}
              selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
              reloadInfoCallback={() => {
                history.push({
                  pathname: '/inventoryPlanController/manage',
                  state: {
                    delRouterNameSource: history.location.pathname,
                  },
                });
              }}
              openFlowChangeModal={setShowSwitchFlow}
              onClose={() => {
                setWorkFlowInfoObj({
                  ...workFlowInfoObj,
                  showWorkFlowModal: false,
                });
                history.push({
                  pathname: '/inventoryPlanController/manage',
                  state: {
                    delRouterNameSource: history.location.pathname,
                  },
                });
              }}
              replaceStrObj={{ own: 'own', workflowType: 'category' }}
            />
          )}
          {/* 挑选流程组件 */}
          {showSwitchFlow && (
            <WorkflowNoDefaultTable
              openVisibleSwitch={showSwitchFlow}
              onCloseSwitch={closeSwitchFlowModal}
              requestController={'assetInventory'}
              orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
              category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`}
              businessCategory={``}
              saveSelectFlowID={(flowId: string) => {
                setWorkFlowInfoObj({
                  ...workFlowInfoObj,
                  saveNoDefaultFlowID: flowId,
                });
              }}
              selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            />
          )}
        </Spin>
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdataView);
